#ifndef __CM_NAT_SEARCH_DAEMON_H__
#define __CM_NAT_SEARCH_DAEMON_H__

#include "MulticastPort.h"
#include "StunMessage.h"
#include "cm_base/BaseTimer.h"
#include "cm_base/ByteBuffer.h"
#include "cm_base/ByteBufferPool.h"
#include "Poco/Net/SocketReactor.h"

namespace  cm_nat
{
    class SearchDaemon;

    class SearchDaemonListener
    {
    public:
        virtual void onSearchClient( SearchDaemon* daemon, SocketAddress clientSa ) = 0;
    };

    //SearchDaemon lives in camera, wait for multicast packet from client that
    //search/scan the available camera in LAN
    class SearchDaemon: public MulticastPortListener
    {
    public:
        SearchDaemon(ByteBufferPool* p_pool, SocketReactor* reactor);
        ~SearchDaemon();

        int setup(IPAddress bindIP, std::string id, std::string pwd);
        int teardown();

        void registerListener( SearchDaemonListener* p_listener );

        void setMediaAddress(SocketAddress mediaAddress);

        //from MulticastPortListener
        void onReceive(MulticastPort*p_port, ByteBuffer* p_data); 

        bool detectMessage(ByteBuffer* data);
        int processMessage( ByteBuffer* data );
        int processSearchRequest( StunMessage* p_sm,const SocketAddress& from );
        int processAuthRequest( StunMessage* p_sm, const SocketAddress& from );

    protected:
        std::string m_username;
        std::string m_pwd;

        ByteBufferPool* m_bufferPool;
        SocketReactor* m_reactor;
        BaseTimer* m_timer;

        MulticastPort* m_port;

        SocketAddress m_daemonMediaAddress;
        SocketAddress m_clientMediaAddress;

        SearchDaemonListener* m_listener;
    };
}


#endif